package com.tuoren.forward.service;

import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.tuoren.forward.entity.Model;
import com.tuoren.forward.entity.dto.ModelDto;
import com.tuoren.forward.entity.req.ModelSearchReq;
import com.tuoren.forward.mapper.ModelMapper;
import com.tuoren.forward.util.AccessTokenUtil;
import com.tuoren.forward.util.Result;
import com.tuoren.forward.util.ResultPage;
import com.tuoren.forward.util.UUIDUtil;

@Service
public class ModelService {

	@Autowired
	ModelMapper modelMapper;
	
	/**
	 * @title 查询产品模型数据
	 * @param req
	 * @return ResultPage<Model>
	 */
	public ResultPage<Model> search(ModelSearchReq req){
		Page<Object> page = PageHelper.startPage(req.getPage(), req.getSize());
		ModelDto dto = new ModelDto();
		BeanUtils.copyProperties(req, dto);
		List<Model> models = modelMapper.select(dto);
		return ResultPage.success(models,page.getTotal());
	}
	
	/**
	 * @title 添加模型
	 * @param req
	 * @return Result
	 */
	public Result add(Model req) {
		String userId = AccessTokenUtil.getUserId();
		Model exist = modelMapper.selectByTitle(req.getTitle());
		if(exist != null) {
			return Result.fail("模型数据存在");
		}
		req.setId(UUIDUtil.get32UUID());
		req.setTenantId(userId);
		modelMapper.insertSelective(req);
		return Result.success();
	}
	
	/**
	 * @title 修改模型
	 * @param req
	 * @return Result
	 */
	public Result edit(Model req) {
		Model exist = modelMapper.selectByTitle(req.getTitle());
		if(exist != null && !exist.getId().equals(req.getId())) {
			return Result.fail("模型数据存在");
		}
		req.setProductId(null);
		req.setTenantId(null);
		modelMapper.updateByPrimaryKeySelective(req);
		return Result.success();
	}
	
	/**
	 * @title 删除模型
	 * @param req
	 * @return Result
	 */
	public Result delete(String id) {
		modelMapper.deleteByPrimaryKey(id);
		return Result.success();
	}
}
